package com.bawei.module_detail

import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.HistoryManager
import com.bawei.module_detail.adapter.CommentAdapter
import com.bawei.module_detail.adapter.MyFragmentAdapter
import com.bawei.module_detail.intent.CommentIntent
import com.bawei.module_detail.model.entity.BulletScreenEntity
import com.bawei.module_detail.model.entity.DanmakuParam
import com.bawei.module_detail.model.entity.VideoEntity
import com.bawei.module_detail.state.CommentState
import com.bawei.module_detail.viewmodel.CommentViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import master.flame.danmaku.ui.widget.DanmakuView
import java.io.File
import java.io.FileOutputStream
import java.net.URL

@Route(path = "/detail/DetailActivity")
class DetailActivity : AppCompatActivity() {
    private lateinit var vip2: ViewPager2
    private lateinit var player: ExoPlayer
    private lateinit var tab: TabLayout
    private lateinit var playerView: PlayerView
    private lateinit var et: EditText
    private lateinit var dan: TextView
    private lateinit var danmu: DanmakuView
    private lateinit var danmakuContext: DanmakuContext
    private lateinit var back: ImageView
    private lateinit var share: ImageView
    private lateinit var videoUser: VideoEntity
    private lateinit var more: ImageView
    private lateinit var textDan: TextView
    private lateinit var adapter: MyFragmentAdapter
    private lateinit var commentAdapter: CommentAdapter
    private val activeDanmakus = mutableMapOf<Long, BaseDanmaku>()
    private var listManmu : List<BulletScreenEntity> = listOf()

    // 新增：ViewModel 和视频 ID
    private lateinit var viewModel: CommentViewModel
    private var isShow = true
    // 每隔一段时间清理一次旧弹幕
    private val shownDanmakuKeys = mutableSetOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_detail)
        initView()

        //tab与vip2联动
        vip2.adapter = adapter
        TabLayoutMediator(tab, vip2) { tab, position ->
            tab.text = when (position) {
                0 -> "简介"
                1 -> "评论"
                else -> null
            }
        }.attach()

        //弹幕初始化
        initDanmaku()
        //视频初始化
        initializePlayerWithPlaylist()

        getBulletScreenInfo(videoUser.item_id)


        // 初始化 CommentAdapter 并设置监听
        commentAdapter = CommentAdapter()
        share.setOnClickListener {
            addDanmaku("kshajd",true)
        }
        back.setOnClickListener {
            onBackPressed()
        }
        more.setOnClickListener {
            showDownloadDialog()
        }
        dan.setOnClickListener {
            et.visibility = View.VISIBLE
            //获取焦点
            et.requestFocus()
            //显示软键盘
            hideSoftKeyBoard(et)
        }
        textDan.setOnClickListener {
            //隐藏弹幕
            isShowDan()
        }
        //发送弹幕
        sendDanmaku()
        handleBulletScreenInfoState()
        startDanmakuPlaybackMonitor()
    }

    private fun isShowDan() {
        if (isShow) {
            textDan.setBackgroundResource(R.drawable.blue_border_no_box)
            danmu.release()
            danmu.visibility = View.GONE
            isShow = false
        } else {
            textDan.setBackgroundResource(R.drawable.blue_border_box)
            initDanmaku()
            danmu.visibility = View.VISIBLE
            getBulletScreenInfo(videoUser.item_id)
            isShow = true
        }
    }

    @OptIn(UnstableApi::class) private fun initializePlayerWithPlaylist() {
        player = ExoPlayer.Builder(this)
            .setSeekBackIncrementMs(5000) // 快退步长5秒
            .setSeekForwardIncrementMs(5000) // 快进步长5秒
            .build()

        playerView.player = player
        val mediaItem = MediaItem.fromUri(videoUser.videopath)
        player.setMediaItem(mediaItem)
        player.prepare()

        // 新增：获取progress参数并seekTo
        val progress = intent.getLongExtra("progress", 0L)
        if (progress > 0) {
            player.seekTo(progress)
        }
        player.playWhenReady = true
    }

    fun initView(){
        vip2 = findViewById(R.id.vip2)
        tab = findViewById(R.id.tab)
        playerView = findViewById(R.id.player)
        et = findViewById(R.id.ets)
        dan = findViewById(R.id.dan)
        danmu = findViewById(R.id.danmaku)
        share = findViewById(R.id.share)
        back = findViewById(R.id.back)
        more = findViewById(R.id.more)
        textDan = findViewById(R.id.text_dan)
        val s= intent.getStringExtra("detail")
        videoUser = Gson().fromJson(s, VideoEntity::class.java)
        adapter = MyFragmentAdapter(
            this,
            pauseVideo = { pauseVideo() },
            playVideo = { playVideo() },
            item_id = videoUser.item_id,
            video_item = s.toString()
        )
        viewModel = ViewModelProvider(this)[CommentViewModel::class.java]
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release() // 必须释放资源！
        //关闭弹幕
        danmu.release()
    }

    fun hideSoftKeyBoard(view: View) {
        view.requestFocus()
        view.postDelayed({
            val imm = view.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
        }, 200)
    }

    private fun initDanmaku() {
        val maxLinesPair = HashMap<Int, Int>()
        maxLinesPair[BaseDanmaku.TYPE_SCROLL_RL] = 5
        maxLinesPair[BaseDanmaku.TYPE_SCROLL_LR] = 3
        maxLinesPair[BaseDanmaku.TYPE_FIX_TOP] = 2

        val overlappingEnablePair = HashMap<Int, Boolean>()
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = false
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_LR] = false
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true

        danmakuContext = DanmakuContext.create()
            .setMaximumLines(maxLinesPair)
            .setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(1.5f)
            .setScaleTextSize(1.2f)
            .preventOverlapping(overlappingEnablePair)
            .setDanmakuTransparency(1.0f) // 不透明
//            .setEnforceUniqueRegistration(true) // 每个弹幕独立注册，不复用

        danmu.apply {
            enableDanmakuDrawingCache(false)
            clear()
            removeAllDanmakus(true)
            prepare(object : BaseDanmakuParser() {
                override fun parse(): IDanmakus {
                    return Danmakus()
                }
            }, danmakuContext)
        }

        danmu.setCallback(object : DrawHandler.Callback {
            override fun updateTimer(timer: DanmakuTimer?) {}
            override fun drawingFinished() {}
            override fun danmakuShown(danmaku: BaseDanmaku?) {
                Log.d("DanmakuDebug", "弹幕已显示: ${danmaku?.text}")
            }
            override fun prepared() {
                danmu.start()
                Log.d("DanmakuDebug", "DanmakuView 已准备就绪")
            }
        })
    }

    fun addDanmaku(text: String, isFlame: Boolean) {
        val danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        danmaku?.text = text
        danmaku?.duration = master.flame.danmaku.danmaku.model.Duration(8000)
        danmaku?.textColor = if (isFlame) 0xFFFF4500.toInt() else getRandomColor()
        danmaku?.textSize = getRandomTextSize()
        danmaku?.time = danmu.currentTime + 1000
        danmaku?.isLive = true

        if (danmaku != null) {
            // 关键修复点：确保 DanmakuView 处于运行状态
            if (!danmu.isPrepared || danmu.isPaused || !danmu.isShown) {
                danmu.prepare(object : BaseDanmakuParser() {
                    override fun parse(): IDanmakus {
                        return Danmakus()
                    }
                }, danmakuContext)
                danmu.start()
            }

            val timestamp = System.currentTimeMillis()
            activeDanmakus[timestamp] = danmaku
            danmu.addDanmaku(danmaku)

            Log.d("DanmakuDebug", "已尝试添加弹幕: $text")
        } else {
            Log.e("DanmakuDebug", "创建弹幕失败，danmaku 为 null")
        }
    }


    private fun getRandomColor(): Int {
        val colors = listOf(
            0xFFFFFFFF.toInt(),
            0xFF00FF00.toInt(),
            0xFF00FFFF.toInt(),
            0xFFFFFF00.toInt(),
            0xFFFF00FF.toInt()
        )
        return colors.random()
    }

    private fun getRandomTextSize(): Float {
        val sizes = listOf(36f, 40f, 44f, 48f)
        return sizes.random()
    }

    //视频暂停
    fun pauseVideo() {
        player.pause()
    }
    //视频播放
    fun playVideo() {
        player.play()
    }

    override fun onPause() {
        super.onPause()
        saveWatchProgress()
    }

    private fun saveWatchProgress() {
        val userId = UserUtils.getCurrentUserId().ifEmpty {UserUtils.getDefaultUserId() } // 获取当前用户ID
        val videoId = videoUser.item_id
        val lastPosition = player.currentPosition
        val title = videoUser.title
        val primaryImg = videoUser.videopath // 或者用封面字段
        val content = videoUser.description ?: ""
        val authorImg = ""
        val authorName = ""
        val progress = if (player.duration > 0) (lastPosition * 100 / player.duration).toInt() else 0
        
        CoroutineScope(Dispatchers.IO).launch {
            val history = HistoryManager.getHistoryByVideoId(videoId)
            if (history == null) {
                // 没有历史，插入
                HistoryManager.addVideoHistory(
                    userId = userId,
                    title = title,
                    primaryImg = primaryImg,
                    content = content,
                    authorImg = authorImg,
                    authorName = authorName,
                    progress = progress,
                    lastPosition = lastPosition,
                    videoId = videoId,
                    videopath = videoUser.videopath
                )
            } else {
                // 已有历史，更新进度
                HistoryManager.updateLastPositionById(history.id, lastPosition)
            }
        }
    }

    private fun showDownloadDialog() {
        val dialog = BottomSheetDialog(this)
        val view = layoutInflater.inflate(R.layout.dialog_download_video, null)
        val tvFileName = view.findViewById<TextView>(R.id.tv_download_filename)
        val btnDownload = view.findViewById<Button>(R.id.btn_download_confirm)
        val btnCancel = view.findViewById<Button>(R.id.btn_download_cancel)
        val fileName = videoUser.videopath.substringAfterLast('/')
        tvFileName.text = fileName
        btnCancel.setOnClickListener { dialog.dismiss() }
        btnDownload.setOnClickListener {
            btnDownload.isEnabled = false
            btnDownload.text = "下载中..."
            GlobalScope.launch(Dispatchers.IO) {
                val result = downloadVideo(videoUser.videopath, fileName)
                launch(Dispatchers.Main) {
                    btnDownload.isEnabled = true
                    btnDownload.text = "下载"
                    if (result) {
                        Toast.makeText(this@DetailActivity, "下载成功", Toast.LENGTH_SHORT).show()
                        dialog.dismiss()
                    } else {
                        Toast.makeText(this@DetailActivity, "下载失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        dialog.setContentView(view)
        dialog.show()
    }

    private fun downloadVideo(url: String, fileName: String): Boolean {
        return try {
            val dir = File(getExternalFilesDir(null), "offline_videos")
            if (!dir.exists()) dir.mkdirs()
            val file = File(dir, fileName)
            URL(url).openStream().use { input ->
                FileOutputStream(file).use { output ->
                    input.copyTo(output)
                }
            }
            // 可在此处插入数据库或本地记录，供我的页面读取
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun sendDanmaku() {
        et.setOnEditorActionListener { v, actionId, event ->

            val text = et.text.toString().trim()
            if (text.isEmpty()) return@setOnEditorActionListener false

            if ((event != null && event.keyCode == android.view.KeyEvent.KEYCODE_ENTER && event.action == android.view.KeyEvent.ACTION_DOWN)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
            ) {

                // 获取当前播放时间作为弹幕时间戳（单位：毫秒）
                val playTime = player.currentPosition
                val danmakuParam = DanmakuParam(
                    content = text,
                    fontcolor = "#FFFFFF", // 默认颜色，可扩展为用户选择
                    itemid = videoUser.item_id.toLong(),
                    playtime_ = playTime.toString()
                )

                // 发送请求
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED) {
                        viewModel.intents.send(CommentIntent.getSendBulletScreenInfo(danmakuParam))
                    }
                }

                // 显示弹幕到屏幕上
                addDanmaku(text, isFlame = true)

                // 清空输入框并隐藏软键盘
                et.setText("")
                et.visibility = View.GONE
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(et.windowToken, 0)
                true
            } else {
                false
            }
        }
    }

    private fun getBulletScreenInfo(videoId: String) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.intents.send(CommentIntent.getBulletScreenInfo(0, videoId))
            }
        }
    }

    private fun handleBulletScreenInfoState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.getBulletScreenInfo.collect { state ->
                    when (state) {
                        CommentState.Empty -> {
                            Log.d("BulletScreen", "弹幕为空")
                        }
                        CommentState.init -> {}
                        is CommentState.onFailed -> {
                            Log.e("BulletScreen", "加载失败: ${state.msg}")
                            Toast.makeText(this@DetailActivity, "弹幕加载失败", Toast.LENGTH_SHORT).show()
                        }
                        is CommentState.onSuccess -> {
                            if (state.type == "putBull") {
                                listManmu = state.list as List<BulletScreenEntity>
                            }
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                // 新增：监听发送弹幕的状态
                viewModel.sendBulletScreenInfo.collect { state ->
                    when (state) {
                        CommentState.init -> {}
                        is CommentState.onFailed -> {
                            Toast.makeText(this@DetailActivity, "弹幕发送失败: ${state.msg}", Toast.LENGTH_SHORT).show()
                        }
                        is CommentState.onSuccess -> {
                            if (state.type == "sendBull") {
                                Toast.makeText(this@DetailActivity, "弹幕发送成功", Toast.LENGTH_SHORT).show()
                            }
                        }
                        else -> {}
                    }
                }
            }
        }
    }

    private fun startDanmakuPlaybackMonitor() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                while (true) {
                    if (player.isPlaying && listManmu.isNotEmpty()) {
                        val currentPosition = player.currentPosition
                        listManmu.forEach {
                            val danmakuTime = it.playtime?.toLongOrNull() ?: 10L
                            val key = "${it.content}_${danmakuTime}"
                            if (danmakuTime in (currentPosition - 200)..(currentPosition + 200) && key !in shownDanmakuKeys) {
                                addDanmaku(it.content, true)
                                shownDanmakuKeys.add(key)
                            }
                        }
                    }
                    kotlinx.coroutines.delay(200)
                }
            }
        }
    }
}
//    private fun initDanmaku() {
//        // 设置最大显示行数
//        val lp: ViewGroup.LayoutParams = binding.dv.layoutParams
//        binding.dv.layoutParams = lp
//
//        // 创建DanmakuContext并配置
//        val danmakuContext = DanmakuContext.create().apply {
//            setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3F)
//            setDuplicateMergingEnabled(false)
//            setScrollSpeedFactor(1.2f)
//        }
//
//        // 创建解析器 - 最终解决方案
//        parser = object : BaseDanmakuParser() {
//            // 使用反射设置context字段
//            init {
//                try {
//                    val field = BaseDanmakuParser::class.java.getDeclaredField("mContext")
//                    field.isAccessible = true
//                    field.set(this, danmakuContext)
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                }
//            }
//
//            override fun parse(): IDanmakus = Danmakus()
//        }
//
//        binding.dv.setCallback(object : DrawHandler.Callback {
//            override fun prepared() {
//                Log.d("Danmaku", "弹幕视图准备就绪") // 添加日志
//                binding.dv.start()
//            }
//            override fun updateTimer(timer: DanmakuTimer?) {}
//            override fun danmakuShown(danmaku: BaseDanmaku?) {}
//            override fun drawingFinished() {}
//        })
//
//        binding.dv.prepare(parser, danmakuContext)
//        binding.dv.enableDanmakuDrawingCache(true)
//    }
//
//    private fun addDanmaku(text: String, color: Int) {
//        runOnUiThread {
//            Log.d("Danmaku", "尝试添加弹幕: $text") // 添加日志
//            // 安全获取context的最终方案
//            val context = try {
//                val field = BaseDanmakuParser::class.java.getDeclaredField("mContext")
//                field.isAccessible = true
//                field.get(parser) as? DanmakuContext ?: run{
//                    Log.e("Danmaku", "获取context失败")
//                    return@runOnUiThread
//                }
//            } catch (e: Exception) {
//                Log.e("Danmaku", "反射获取context异常", e)
//                return@runOnUiThread
//            }
//
//            val danmaku = context.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL) ?: run {
//                Log.e("Danmaku", "创建弹幕对象失败")
//                return@runOnUiThread
//            }
//
//            danmaku.apply {
//                this.text = text
//                padding = 5
//                priority = 0
//                isLive = true
//                setTime(binding.dv.currentTime)
//                textSize = 25f * (context.displayer.density - 0.6f)
//                textColor = color
//                textShadowColor = 0
//            }
//            Log.d("Danmaku", "即将显示弹幕: ${danmaku.text}") // 添加日志
//            binding.dv.addDanmaku(danmaku)
//        }
//    }